
--TMXTiledMap class
TMXTiledMap = {
	blockData = nil,
	updateID = nil,
}

TMXTiledMap.__index = TMXTiledMap

function TMXTiledMap:onEnter()
	Misc:log("Menu : onEnter .. " .. Misc:getNodeName(self))
	
	local function update()
    end	
	self.updateID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(update, 1/60.0, false)
end

function TMXTiledMap:onExit()
	CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(self.updateID)
end

function TMXTiledMap:blockAt(pos)
	local anchorPoint = self:getAnchorPoint()
	local size = self:getContentSize()
	local tiledSize = self:getTileSize()
	local mapSize = self:getMapSize()
	local leftBottom = CCPoint(-size.width*anchorPoint.x, -size.height*anchorPoint.y)
	local offset = ccpSub(pos, leftBottom)
	local scaleFactor = CCDirector:sharedDirector():getContentScaleFactor()
	
	--Misc:log("............leftBottom....."..leftBottom.x..".................."..leftBottom.y)
	--Misc:log("............offset....."..offset.x..".................."..offset.y)
	local x = math.floor(offset.x/tiledSize.width*scaleFactor)
	local y = math.floor(offset.y/tiledSize.height*scaleFactor)
	--Misc:log("...................."..x..".................."..y)
	
	local index = y*mapSize.width + x
	if index >= table.getn(self.blockData) or index < 0 then
		return 0
	end
	
	return self.blockData[index]
end

function TMXTiledMap:initBlockData(blockFile)
	local tiledSize = self:getTileSize()
	local mapSize = self:getMapSize()
	---------------------------------------
	local file = assert(io.open(blockFile, "r"))
	file:read("*n")
	file:read("*n")
	local readValue = nil
	local nCount = 0
	repeat
		readValue = file:read("*n")
		if readValue then
			self.blockData[nCount] = readValue
			--test
			--if readValue == 1 then
			--	local blk = CCSprite:create("HelloWorld.png")
			--	blk:setTextureRect(CCRect(0,0,tiledSize.width*0.5-2, tiledSize.height*0.5-2))
			--	self:addChild(blk, 10)
			--	local pos = CCPoint(tiledSize.width*0.5*(0.5+(nCount%mapSize.height)), tiledSize.height*0.5*(0.5+math.floor(nCount/mapSize.height)))
				--blk:setPosition(pos.x, pos.y)
				--Misc:log("--------------="..pos.x.."--------="..pos.y.."---"..nCount.. " -- "..mapSize.height)
			--end
			nCount = nCount + 1
		end
	until not readValue
	-----------------------------------------
end

function TMXTiledMap:create(mapFile, blockFile)
	local newMap = {}
	newMap.blockData = {}
	setmetatable(newMap, self)
	--self.__index = self
	local ccMap = CCTMXTiledMap:create(mapFile)
	
	tolua.setpeer(ccMap, newMap)

	ccMap:initBlockData(blockFile)
	
	local function onEnterOrExit(eventType)
		if eventType == kCCNodeOnExit then
			ccMap:onExit()
		else
			ccMap:onEnter()
		end
	end
	
	ccMap:registerScriptHandler(onEnterOrExit)
	
	if ccMap:isRunning() then
		ccMap:onEnter()
	end
	return ccMap
end
